// src/components/ImageItem.js
import React, { useEffect, useState } from 'react';
import { useDrag } from 'react-dnd';
import { Card, CardMedia, CardContent, Typography, Skeleton } from '@mui/material';
import { getEmptyImage } from 'react-dnd-html5-backend';

const ItemTypes = {
  IMAGE: 'image',
};

const ImageItem = ({ image, index }) => {
  const [{ isDragging }, drag, preview] = useDrag({
    type: ItemTypes.IMAGE,
    item: () => ({ ...image, index }),
    collect: (monitor) => ({
      isDragging: !!monitor.isDragging(),
    }),
  });

  const [imageUrl, setImageUrl] = useState('');
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    preview(getEmptyImage(), { captureDraggingState: true });
  }, [preview]);

  useEffect(() => {
    let isMounted = true;
    const loadImage = async () => {
      const url = URL.createObjectURL(image.file);
      if (isMounted) {
        setImageUrl(url);
        setIsLoading(false);
      }
    };
    loadImage();
    return () => {
      isMounted = false;
      URL.revokeObjectURL(imageUrl);
    };
  }, [image.file]);

  return (
    <Card
      ref={drag}
      sx={{
        opacity: isDragging ? 0.5 : 1,
        cursor: 'move',
        height: '200px',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {isLoading ? (
        <Skeleton variant="rectangular" sx={{ flexGrow: 1 }} />
      ) : (
        <CardMedia
          component="img"
          sx={{ flexGrow: 1, objectFit: 'cover' }}
          image={imageUrl}
          alt={image.name}
          loading="lazy"
        />
      )}
      <CardContent sx={{ flexShrink: 0 }}>
        <Typography variant="body2" noWrap>
          {image.name}
        </Typography>
      </CardContent>
    </Card>
  );
};

export default ImageItem;